package middleware

import (
	"strings"
	"time"

	"github.com/gin-gonic/gin"

	"server/internal/app/dto"
	"server/internal/app/service"
	"server/internal/core/server"
)

const (
	ContextAdminKey   = "currentAdmin"
	ContextAdminIDKey = "currentAdminID"
)

var authService = service.NewAdminAuthService()

func Auth() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		token := ctx.GetHeader("Authorization")
		if token == "" {
			server.DefaultController.Error(ctx, server.UnauthorizedError)
			ctx.Abort()
			return
		}
		token = strings.TrimPrefix(token, "Bearer ")
		token = strings.TrimSpace(token)
		if token == "" {
			server.DefaultController.Error(ctx, server.UnauthorizedError)
			ctx.Abort()
			return
		}

		//验证token
		adminTokenInfo, err := authService.ParseToken(ctx, token)
		if err != nil {
			server.DefaultController.Error(ctx, err)
			ctx.Abort()
			return
		}

		//token已过期
		if adminTokenInfo.ExpiredAt < time.Now().Unix() {
			server.DefaultController.Error(ctx, server.UnauthorizedError)
			ctx.Abort()
			return
		}

		ctx.Set(ContextAdminKey, adminTokenInfo.AdminID)
		ctx.Set(ContextAdminIDKey, adminTokenInfo.AdminID)
		ctx.Next()
	}
}

// GetCurrentAdminID 获取当前管理员ID
func GetCurrentAdminID(ctx *gin.Context) uint {
	adminID, ok := ctx.Get(ContextAdminIDKey)
	if !ok {
		return 0
	}
	return adminID.(uint)
}

// GetCurrentAdmin 获取当前管理员
func GetCurrentAdmin(ctx *gin.Context) *dto.AdminTokenInfo {
	adminID, ok := ctx.Get(ContextAdminKey)
	if !ok {
		return nil
	}
	return adminID.(*dto.AdminTokenInfo)
}
